/*
 * @Author: yixin 
 * @Date: 2019-12-10 23:55:09 
 * @Last Modified by: yixin
 * @Last Modified time: 2020-01-09 20:19:20
 * 设备画像
 */
import React, { Component } from "react"
import { withRouter } from "react-router"
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/chart/line';
import 'echarts/lib/chart/custom';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/legendScroll';
import 'echarts/lib/component/dataZoom';
import 'echarts/lib/component/dataZoomInside';
import styles from './devPortrait.less'
import Header from '@/components/header'
import { formatDate, formatFullDate, getChartColor } from '@/utils'
import { equipOneChart } from '@/services'
import { formatStatus, formatColor, getQueryString, renderItem, formatTime  } from '@/utils/protarit'

class DevPortrait extends Component {

  constructor(props){
    super(props);
    this.times = getQueryString('worktime') ? JSON.parse(getQueryString('worktime'))
    : {
      beginDate: formatDate(new Date()), 
      endDate: formatDate(new Date())
    };
    this.equipCode = getQueryString('equipCode');
    this.token = getQueryString('token');
    this.source = getQueryString('source');
  }

  componentDidMount() {
    this.mql = window.matchMedia('(orientation: portrait)');
    
    // 监听屏幕模式变化
    this.mql.addListener(this.onMatchMediaChange);
    this.renderChart()
  }

  componentWillUnmount() {
    this.mql.removeListener(this.onMatchMediaChange);
  }

  onMatchMediaChange = (mql) => {
    this.chart.resize();
    setTimeout(()=>{ this.chart.resize(); }, 1000)
  }

  renderChart = async() => {
    try {
    const { data } = await equipOneChart({ equipCode: this.equipCode , ...this.times, token: this.token, source: this.source });
    // 用透明的数据撑起24小时时间区间
    const anchorLine = [
      [`${this.times.beginDate} 00:00:00`, 0],
      [`${this.times.beginDate} 24:00:00`, 0],
    ];
    this.chart = echarts.init(document.getElementById('chart'));
    this.seriesData = [];
    this.oilData = [];
    this.quantityData = [];
    this.mileData = []
    data.stateList.map(item=>{
      this.seriesData.push({
        name: '状态',
        value: [0, item.startTime, item.endTime, item.equipState],
        itemStyle: {
          normal: {
            color: formatColor(item.equipState)
          }
        }
      })
    })
    data.dataList.map(item=>{
      this.oilData.push([item.time, item.oil]);
      this.quantityData.push([item.time, item.quantity])
      this.mileData.push([item.time, item.mileage])
    })
    this.chart.setOption({
      axisPointer: {
        link: [
          {
            xAxisIndex: [0, 1],
          },
        ],
      },
      grid: [{
        top: 50,
        left: 35,
        right: 30,
        bottom: '25%',
      },{
        top: '80%',
        left: 35,
        right: 30,
        bottom: 35
      }],
      xAxis: [{
        type: 'time',
        gridIndex: 0,
        axisLabel: {
          show: false,
        },
        splitLine: {
          show: false,
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false,
        },
        splitNumber: 12
      },{
        gridIndex: 1,
        type: 'time',
        splitNumber: 12,
        splitLine: {
          show: false,
        },
        axisLabel: {
          formatter: (value)=>{
            const date = new Date(value)
            return `${date.getHours()<10 ? '0' : ''}${date.getHours()}:${date.getMinutes()<10 ? '0' : ''}${date.getMinutes()}`
          }
        }
        
      }],
      yAxis: [{
        name: '千米',
        type: 'value',
        splitLine: {
          show: false
        },
        splitNumber: 5,
        axisLabel: {
          show: true,
          formatter: (value)=>{ 
            return (value/1000).toFixed(1)
          },
        }
      },{
        name: '方｜L',
        type: 'value',
        splitLine: {
          show: false
        },
        splitNumber: 5,
        axisLabel: {
          show: true,
          formatter: '{value}'
        }
      },{
        gridIndex: 1,
        axisLabel: {
          show: false,
        },
        axisTick: {
          show: false,
        },
      },{
        gridIndex: 1,
        axisLabel: {
          show: false,
        },
        axisTick: {
          show: false,
        },
      }],
      tooltip: {
        trigger: 'axis',
        triggerOn: 'click',
        formatter: (params) => {
          if(params.length<4){
            return ``
          }
          if(params[0].componentIndex===0){
            return `
              ${formatFullDate(params[0].axisValue)}<br />
              状态：${formatStatus(params[3].value[3])} ${formatTime((params[3].value[2]-params[3].value[1])/1000)}<br />
              油耗(升)：${params[2].data[1]}<br />
              泵送方量(方)：${params[1].data[1]}<br />
              行驶里程(米)：${params[0].data[1]}
            `
          }else{
            return `
              ${formatStatus(params[0].value[3])}: ${formatTime((params[0].value[2]-params[0].value[1])/1000)}<br />
            `
          }
        }
      },
      dataZoom: [
        {
          type: "inside",
          xAxisIndex: [0, 1],
          yAxisIndex: null,
          filterMode: 'weakFilter',
          preventDefaultMouseMove: false
        },
      ],
      legend: {
        data:['行驶','驻车','泵送','转场','待料','行驶里程','泵送方量','油耗'],
        top: 10
      },
      series: [{ 
        name: '行驶里程',
        type: 'line',
        data: this.mileData,
        showSymbol: false,
        smooth: 'average',
        itemStyle: {
          color: getChartColor['行驶里程'],
        },
        yAxisIndex: 0,
        xAxisIndex: 0,
      },{ 
        name: '泵送方量',
        type: 'line',
        data: this.quantityData,
        showSymbol: false,
        smooth: 'average',
        itemStyle: {
          color: getChartColor['泵送方量'],
        },
        yAxisIndex: 1,
        xAxisIndex: 0,
        label: {
          show: true,
          formatter: '{b}'
        },
      },{ 
        name: '油耗',
        type: 'line',
        data: this.oilData,
        showSymbol: false,
        smooth: 'average',
        itemStyle: {
          color: getChartColor['油耗'],
        },
        yAxisIndex: 1,
        xAxisIndex: 0,
      },{
        value: '状态',
        type: 'custom',
        renderItem: renderItem,
        encode: {
            x: [1, 2],
            y: 0
        },
        data: this.seriesData,
        yAxisIndex: 2,
        xAxisIndex: 1,
      },{
          name: '行驶',
          type: 'custom',
          itemStyle: {
            normal: {
              color: getChartColor['行驶']
            }
          },
      },{
          name: '驻车',
          type: 'custom',
          itemStyle: {
            normal: {
              color: getChartColor['驻车']
            }
          },
      },{
          name: '泵送',
          type: 'custom',
          itemStyle: {
            normal: {
              color: getChartColor['泵送']
            }
          },
      },{
          name: '转场',
          type: 'custom',
          itemStyle: {
            normal: {
              color: getChartColor['转场']
            }
          },
      },{
          name: '待料',
          type: 'custom',
          itemStyle: {
            normal: {
              color: getChartColor['待料']
            }
          },
      },{ 
        name: '时间区间',
        type: 'line',
        data: anchorLine,
        itemStyle:{normal:{opacity:0}},
        lineStyle:{normal:{opacity:0}},
        yAxisIndex: 0,
        xAxisIndex: 0,
      },{ 
        name: '时间区间',
        type: 'line',
        data: anchorLine,
        showSymbol: false,
        itemStyle:{normal:{opacity:0}},
        lineStyle:{normal:{opacity:0}},
        yAxisIndex: 2,
        xAxisIndex: 1,
      }]
    })
    } catch (error) {
      console.log(error)
    }
  }

  render(){
    return(
      <div style={{ width: '100%' }}>
        <div className={styles.devPortrait}>
          <div className={styles.header}>
            <div onClick={()=>{ this.props.history.goBack() }} className={styles.back}>
              <img src={require('../assets/img/back.png')} />
            </div>
            <div >
              <div className={styles.header_title}>设备画像（{this.equipCode}）</div>
              <div className={styles.header_time}>{this.times.beginDate===this.times.endDate ? this.times.beginDate : `${this.times.beginDate} / ${this.times.endDate}`}</div>
            </div>
          </div>
          <div id="chart" className={styles.chart}></div>
        </div>
      </div>
    )
  }
}

export default withRouter(DevPortrait)